package com.template.templateuser.domain.service;

import com.template.templatecommon.domain.Result;
import com.template.templateuser.domain.dto.SysDeptDTO;
import com.template.templateuser.domain.dto.SysUserDTO;
import com.template.templateuser.domain.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<SysUserDTO> getSysUserList() {
        return sysUserMapper.getSysUserList();
    }

    @Override
    public int saveUser(SysUserDTO sysUserDTO) {
        int count=sysUserMapper.queryByContion(sysUserDTO);
        if(count==0){
            String finalSecret = new BCryptPasswordEncoder().encode(sysUserDTO.getPassword());
            sysUserDTO.setPassword(finalSecret);
            sysUserDTO.setSalt(finalSecret);
            return sysUserMapper.saveUser(sysUserDTO);
        }else{
            throw new RuntimeException("用户名或手机号或邮箱已经存在！");
        }
    }

    @Override
    public SysUserDTO findUserByLoginName(String loginName) {
        return sysUserMapper.findUserByLoginName(loginName);
    }

    @Override
    public Result deleteUser(Long userId) {
        SysUserDTO deletedUser=new SysUserDTO();
        deletedUser.setId(userId);
        deletedUser.setDeleted(1);
        return Result.success(sysUserMapper.updateUserByUserId(deletedUser));
    }

    @Override
    public SysUserDTO querySysUser(Long id) {
        return sysUserMapper.findById(id);
    }

    @Override
    public int updateSysUser(Long id, SysUserDTO sysUserDTO) {
        sysUserDTO.setId(id);
        return sysUserMapper.updateUserByUserId(sysUserDTO);
    }
}
